<?php
/**
 * Created by PhpStorm.
 * User: zsd
 * Date: 2018/5/3
 * Time: 下午2:18
 */
namespace backend\controllers;

use common\controllers\BaseController;
use common\traits\DataProviderPagination;
use mdm\admin\components\MenuHelper;
use mdm\admin\models\Assignment;
use mdm\admin\models\searchs\AuthItem;
use Yii;
use yii\filters\VerbFilter;
use yii\rbac\Item;
use yii\web\BadRequestHttpException;

class AuthController extends BaseController
{
    use DataProviderPagination;

    public function verbs()
    {
        return [
            'assignment-assign' => ['post'],
            'assignment-revoke' => ['post'],
        ];
    }

    /**
     * 分配角色
     *
     * @param $id
     *
     * @throws \yii\web\BadRequestHttpException
     */
    public function actionAssignmentAssign($id)
    {
        $items   = Yii::$app->request->body('items');
        $model   = new Assignment($id);
        $success = $model->assign($items);

        if ($success <= 0) {
            throw new BadRequestHttpException('用户权限分配失败');
        }

        return true;
    }

    /**
     * 移除角色
     *
     * @param $id
     *
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function actionAssignmentRevoke($id)
    {
        $items   = Yii::$app->request->body('items');
        $model   = new Assignment($id);
        $success = $model->revoke($items);

        if ($success <= 0) {
            throw new BadRequestHttpException('用户权限移除失败');
        }

        return true;
    }

    /**
     * 获取菜单列表
     *
     * @return array
     */
    public function actionMenuLists()
    {
        return MenuHelper::getAssignedMenu(Yii::$app->user->id);
    }

    /**
     * 获取授权列表
     *
     * @return array
     */
    public function actionPermissionLists()
    {
        $model       = new AuthItem();
        $model->type = Item::TYPE_PERMISSION;

        $dataProvider = $model->search(Yii::$app->getRequest()->get());

        return $this->returnPagination($dataProvider);
    }

    /**
     * 获取角色列表
     *
     * @return array
     */
    public function actionRoleLists()
    {
        $model       = new AuthItem();
        $model->type = Item::TYPE_ROLE;

        $dataProvider = $model->search(Yii::$app->getRequest()->get());

        return $this->returnPagination($dataProvider);
    }
}
